#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
Date   : 2020-01-21
"""
from mmonitor.common import vars as vr
from mmonitor.utils.send_mail import send_mail
from mmonitor.models.mysql_db import UserModel, AlertConfigModel, WebSiteModel
import logging
from mmonitor.utils.change_time import change_time


class Notify(object):
    def __init__(self):
        self.mail_template = ""
        self.send_to = []

    def get_contact(self, url_id):
        res = AlertConfigModel.select().where(AlertConfigModel.url_id == url_id)
        return [i.alert_contact.email for i in res] or [self.get_mail_by_url_id(url_id)]

    def get_url(self, url_id):
        res = WebSiteModel.get_by_id(url_id)
        return res.url

    def get_mail_by_url_id(self, url_id):
        res = WebSiteModel.get_by_id(url_id)
        return res.user_id.email

    def send_mail(self, to, title, content, cc=""):
        send_mail(to, subject=title, body=content)

    def process(self, url_id, status_code, error_ts):
        raise NotImplementedError


class Alert(Notify):

    def __init__(self):
        super(Alert, self).__init__()

    def process(self, url_id, status_code, error_ts):
        to = self.get_contact(url_id)
        body = "您监控的网站:{} 访问异常，故障持续时间:{}".format(self.get_url(url_id), change_time(error_ts))

        for t in to:
            self.send_mail(t, "网站故障预警", body)


class Recovery(Notify):

    def __init__(self):
        super(Recovery, self).__init__()

    def process(self, url_id, status_code, error_ts):
        to = self.get_contact(url_id)
        body = "您监控的网站:{} 恢复正常访问，故障持续时间:{}".format(self.get_url(url_id), change_time(error_ts))

        for t in to:
            logging.info('要发送给:{}'.format(t))

            self.send_mail(t, "网站恢复通知", body)


class Send(object):

    def __init__(self):
        self._worker_flow = dict()

    @property
    def worker_flow(self):
        if not self._worker_flow:
            self._worker_flow = {
                vr.s_alert_type: Alert(),
                vr.s_recovery_type: Recovery()
            }
        return self._worker_flow

    def process(self, url_id, status_code, error_ts, send_type):
        action = self.worker_flow.get(send_type)
        if action is None:
            logging.error("type error :{}".format(send_type))
            return
        action.process(url_id, status_code, error_ts)


if __name__ == "__main__":
    s = Send()
    url_id = 4
    status_code = 0
    error_ts = 1000
    # s.process(url_id, status_code, error_ts, send_type=vr.s_alert_type)
    n = Notify()
    n.get_mail_by_url_id(4)


